package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    @Transactional
    public void saveWithDish(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);

        //保存套餐数据
        baseMapper.insert(setmeal);
        //获取套餐的id
        Long setmealId = setmeal.getId();

        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes.forEach(
                setmealDish -> setmealDish.setSetmealId(setmealId)
        );
        setmealDishMapper.insertBatch(setmealDishes);
    }

    @Override
    public PageResult page(SetmealPageQueryDTO setmealPageQueryDTO) {
        Page<Setmeal> setmealPage = baseMapper.selectPage(
                new Page<>(setmealPageQueryDTO.getPage(), setmealPageQueryDTO.getPageSize()),
                new LambdaQueryWrapper<Setmeal>()
                        .like(StringUtils.isNotBlank(setmealPageQueryDTO.getName()),
                                Setmeal::getName, setmealPageQueryDTO.getName())
                        .eq(setmealPageQueryDTO.getCategoryId() != null,
                                Setmeal::getCategoryId, setmealPageQueryDTO.getCategoryId())
                        .eq(setmealPageQueryDTO.getStatus() != null,
                                Setmeal::getStatus, setmealPageQueryDTO.getStatus())
                        .orderByDesc(Setmeal::getUpdateTime)
        );

        return new PageResult(setmealPage.getTotal(), setmealPage.getRecords());
    }

    @Override
    public void deleteBatch(List<Long> ids) {
        if (ids == null || ids.size() == 0) {
            throw new IllegalArgumentException("删除的套餐ID列表不能为空");
        }
        List<Setmeal> setmeals = this.listByIds(ids);
        setmeals.forEach(setmeal -> {
            if (setmeal.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
            }
        });
        //删除套餐
        this.removeByIds(ids);
        //批量删除套餐关联的菜品信息
        setmealDishMapper.delete(
                new LambdaQueryWrapper<SetmealDish>()
                        .in(SetmealDish::getSetmealId, ids)
        );
    }

    /**
     * 根据id查询套餐和套餐关联的菜品信息
     *
     * @param id
     * @return
     */
    @Override
    public SetmealVO getByIdWithDish(Long id) {
        Setmeal setmeal = getById(id);
        if (setmeal == null) {
            throw new RuntimeException("套餐不存在");
        }
        List<SetmealDish> setmealDishes = setmealDishMapper.selectList(
                new LambdaQueryWrapper<SetmealDish>()
                        .eq(SetmealDish::getSetmealId, id)
        );
        SetmealVO setmealVO = new SetmealVO();
        BeanUtils.copyProperties(setmeal, setmealVO);
        setmealVO.setSetmealDishes(setmealDishes);
        return setmealVO;
    }

    /**
     * 修改套餐
     * @param setmealDTO
     */
    @Transactional
    @Override
    public void updateSetmeal(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        updateById(setmeal);
        Long id = setmeal.getId();
        setmealDishMapper.delete(new LambdaQueryWrapper<SetmealDish>().eq(SetmealDish::getSetmealId, id));
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes.forEach(
                setmealDish -> {
                    setmealDish.setSetmealId(id);
                }
        );
        setmealDishMapper.insertBatch(setmealDishes);
    }

    /**
     * 批量起售停售
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        // 只有在启用套餐时才需要检查关联菜品状态
        if (status == StatusConstant.ENABLE) {
            List<SetmealDish> setmealDishes = setmealDishMapper.selectList(new LambdaQueryWrapper<SetmealDish>()
                    .eq(SetmealDish::getSetmealId, id)
            );
            for (SetmealDish setmealDish : setmealDishes) {
                Dish dish = dishMapper.selectById(setmealDish.getDishId());  // 注意这里是getDishId()
                if (dish == null) {
                    throw new DeletionNotAllowedException("关联菜品不存在");
                }
                if (dish.getStatus() == StatusConstant.DISABLE) {
                    throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                }
            }
        }
        Setmeal setmeal = Setmeal.builder()
                .id(id)
                .status(status)
                .build();
        updateById(setmeal);
    }

    @Override
    public List<Setmeal> listSetmeal(Setmeal setmeal) {
        List<Setmeal> setmealList = baseMapper.selectList(
                new LambdaQueryWrapper<Setmeal>()
                        .eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId())
                        .eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus())
                        .orderByDesc(Setmeal::getUpdateTime)
        );
        return setmealList;
    }

    @Override
    public List<DishItemVO> getDishItemById(Long id) {
        List<DishItemVO> dishItemList = setmealMapper.getDishItemBySetmealId(id);
        return dishItemList;
    }
}
